import React from 'react';
import { Form, Button, Input, notification } from 'antd';
import { updatePass } from '../api/user';

const FormItem = Form.Item;

class UpdatePasswordForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();

    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return;
      }
      
      updatePass(fieldsValue).then(res => {
        const { data } = res
        if (data.code === 1) {
          notification.error({
            message: data.msg
          })
        } else if (data.code === 0) {
          notification.success({
            message: data.msg
          })
          this.props.form.resetFields()
        }
      })
      .catch(err => {
        notification.error(err)
      })
    });
  }

  validateNewPass = (rule, value, cb) => {
    const { newpass, newPassAgain } = this.props.form.getFieldsValue(['newpass', 'newPassAgain'])
    if(newpass === newPassAgain)
      cb()
    else
      cb('两次密码输入不一致')
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem
          {...formItemLayout}
          label="请输入旧密码"
        >
          {getFieldDecorator('oldpass', {rules: [
            { required: true },
          ]})(
            <Input
              placeholder="请输入旧密码"
              type="password"
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="请输入新密码"
        >
          {getFieldDecorator('newpass', {rules: [
            { required: true },
          ]})(
            <Input
              placeholder="请输入新密码"
              type="password"
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="请重复新密码"
        >
          {getFieldDecorator('newPassAgain', {rules: [
            { required: true },
            { validator: this.validateNewPass }
          ]})(
            <Input
              placeholder="请重复新密码"
              type="password"
            />
          )}
        </FormItem>
        <FormItem
          wrapperCol={{
            xs: { span: 24, offset: 0 },
            sm: { span: 16, offset: 8 },
          }}
        >
          <Button type="primary" htmlType="submit">修改</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedUpdatePasswordForm = Form.create()(UpdatePasswordForm);

export default WrappedUpdatePasswordForm
